package com.sjf.reggie.controller;

import com.sjf.common.Result;
import com.sjf.reggie.entity.AddressBook;
import com.sjf.reggie.service.AddressBookService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 地址簿 控制器
 *
 * @author <huangtang>
 * @since 2022/4/27 10:40
 **/
@Slf4j
@Api(tags="地址相关接口")
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 查询所有地址簿
     * @return
     */
    @GetMapping("/list")
    public Result<List<AddressBook>> getList( HttpSession session ){
       List<AddressBook> addressBooksList =  addressBookService.getList(session);
       return Result.success(addressBooksList);
    }

    @GetMapping("/{id}")
    public Result<AddressBook> getById(@PathVariable("id") Long id){
        AddressBook addressBook = addressBookService.getById(id);
        return Result.success(addressBook);
    }

    /**
     * 添加地址
     * @param addressBook
     * @return
     */
    @PostMapping()
    public Result<String> save( @RequestBody AddressBook addressBook){
        log.info("添加地址:{}",addressBook);
        boolean result = addressBookService.add(addressBook);
        return result? Result.success("添加成功"):Result.error ("添加失败");
    }

    /**
     * 修改地址
     * @param addressBook
     * @return
     */
    @PutMapping()
    public Result<String> updateAddress(@RequestBody AddressBook addressBook){
        log.info ("修改地址信息:{}",addressBook);
        boolean result = addressBookService.updateAddress(addressBook);
        return result? Result.success("修改成功"):Result.error ("修改失败");
    }

    /**
     * 删除地址
     * @param ids
     * @return
     */
    @DeleteMapping()
    public Result<String> deleteAddress( String ids){
        log.info ("删除地址信息:{}",ids);
        boolean result = addressBookService.removeById (ids);
        return result? Result.success("删除成功"):Result.error ("删除失败");
    }

    /**
     * 将地址设为默认地址
     * @param addressBook
     * @return
     */
    @PutMapping("/default")
    public Result<String> setDefaultAddressApi(@RequestBody AddressBook addressBook){
        log.info("设置默认地址:{}",addressBook);
        boolean result = addressBookService.setDefaultAddress(addressBook);
        return result? Result.success("设置成功"):Result.error ("设置失败");
    }

    @GetMapping("/default")
    public Result<AddressBook> getAddress(){
        log.info("获取当前用户默认地址");
        AddressBook addressBook = addressBookService.getAddress();
        return Result.success (addressBook);
    }
}
